package com.dollkey.packagemanager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

public abstract class BasePopupWindow extends PopupWindow {

    protected View contentView;
    protected View mParentView;
    protected Context mContext;

    public BasePopupWindow(Context context, OnDismissListener onDismiss) {
        this(context, onDismiss, true);
    }

    public BasePopupWindow(Context context, OnDismissListener onDismiss, boolean canOutsideDismiss) {
        super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContext = context;
        mParentView = ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content);
        LayoutInflater inflater = LayoutInflater.from(context);

        contentView = initView(inflater);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setElevation(1f);
        }
        if (canOutsideDismiss) {
            setBackgroundDrawable(new BitmapDrawable());
            setOutsideTouchable(true);
            setFocusable(true);
        }
        setOnDismissListener(onDismiss);
        setContentView(contentView);

    }

    protected abstract View initView(LayoutInflater inflater);

    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }

    public void showAtCenter() {
        showAtLocation(mParentView, Gravity.CENTER,0,0);
    }
}
